package com.gzh.system.service.impl;

import com.gzh.core.dao.mapper.FileMapper;
import com.gzh.core.dao.mapper.UserMapper;
import com.gzh.core.dao.po.FileEntity;
import com.gzh.core.dao.po.UserEntity;
import com.gzh.core.util.CosUtils;
import com.gzh.core.util.JwtUtil;
import com.gzh.core.util.NumericHelper;
import com.gzh.core.util.StringUtils;
import com.gzh.core.util.constant.ErrorCode;
import com.gzh.core.util.exception.BusinessException;
import com.gzh.system.model.vo.PwdParam;
import com.gzh.system.service.UserService;
import com.gzh.system.service.dto.LoginIn;
import com.gzh.system.service.dto.LoginOut;
import com.gzh.system.service.dto.RegisterIn;
import com.gzh.system.service.dto.RegisterOut;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static io.jsonwebtoken.impl.TextCodec.BASE64;

/**
 * @Author guanzh
 * @Date 2022/3/2 14:41
 * @Description
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LoginOut login(LoginIn in, HttpServletResponse response) {
        LoginOut out = new LoginOut();
        UserEntity userQuery = new UserEntity();
        String userName = in.getUserName();
        if (userName.contains("@")){
            userQuery.setMail(userName);
        }else {
            userQuery.setTel(userName);
        }
        UserEntity user = userMapper.selectOne(userQuery);
        if (user == null) {
            throw new BusinessException(ErrorCode.LOGIN_001);
        } else {
            if (!in.getPassword().equals(user.getPassword())) {
                throw new BusinessException(ErrorCode.LOGIN_002);
            } else {
                String img = user.getImg();
                if (img != null){
                    FileEntity fileEntity = new FileEntity();
                    fileEntity.setFileId(NumericHelper.toInteger(img));
                    List<FileEntity> fileEntityList = fileMapper.select(fileEntity);
                    if (!CollectionUtils.isEmpty(fileEntityList)){
                        FileEntity entity = fileEntityList.get(0);
                        String imgPath = CosUtils.getImg(entity.getBucketName(), entity.getPath());
                        out.setImgPath(imgPath);
                    }
                }
                out.setUserId(StringUtils.toString(user.getUserId()));
                out.setFullName(user.getFullName());
                out.setMail(user.getMail());
                out.setTel(user.getTel());
                out.setSex(StringUtils.toString(user.getSex()));
                out.setSchoolId(user.getSchoolId());
                String token = JwtUtil.createJWT(6000000, user);
                out.setToken(token);
                return out;
            }
        }
    }

    @Override
    public RegisterOut register(RegisterIn in) {
        RegisterOut registerOut = new RegisterOut();
        String mail = in.getMail();
        String tel = in.getTel();
        if (StringUtils.isNotEmpty(in.getVerifyCode())){
            String code = (String) redisTemplate.opsForValue().get(tel);
            if (!(in.getVerifyCode().toLowerCase()).equals(code.toLowerCase())){
                throw new BusinessException(ErrorCode.REGISTER_001);
            }
        }
        if (StringUtils.isEmpty(tel)){
            throw new BusinessException(ErrorCode.REGISTER_002);
        }
        Condition userCondition = new Condition(UserEntity.class);
        Example.Criteria criteria = userCondition.createCriteria();
        criteria.andEqualTo("tel",tel);
        List<UserEntity> userEntityList = userMapper.selectByCondition(userCondition);
        UserEntity userEntity = new UserEntity();
        if (CollectionUtils.isEmpty(userEntityList)){
            userEntity.setTel(StringUtils.trimNull(tel));
            userEntity.setPassword(StringUtils.trimNull(in.getPassword()));
            userMapper.insertSelective(userEntity);
        }else {
            userEntity.setFullName(StringUtils.trimNull(in.getFullName()));
            userEntity.setMail(StringUtils.trimNull(mail));
            userEntity.setSex(NumericHelper.zeroNull(in.getSex()));
            userEntity.setSchoolId(NumericHelper.zeroNull(in.getSchoolId()));
            userEntity.setGrade(NumericHelper.zeroNull(in.getGrade()));
            userEntity.setClassId(NumericHelper.zeroNull(in.getClassId()));
            userEntity.setAcademyId(NumericHelper.zeroNull(in.getAcademyId()));
            userEntity.setRoleId(NumericHelper.zeroNull(in.getRoleId()));
            userMapper.updateByConditionSelective(userEntity,userCondition);
        }
        return registerOut;
    }

    @Override
    public String updateImg(UserEntity user) {
        String img = user.getImg();
        if (img == null){
            return null;
        }
        String base64=img.split(",")[1];
        byte[] result=BASE64.decode(new String(base64));
        String path = CosUtils.upload(result, "picture-1307568725", "img");
        FileEntity fileEntity = new FileEntity();
        fileEntity.setBucketName("picture-1307568725");
        fileEntity.setPath(path);
        fileEntity.setFileName(path.substring(path.indexOf("/")));
        fileEntity.setClassify("avatar");
        fileMapper.insertSelective(fileEntity);
        Condition condition = new Condition(UserEntity.class);
        condition.createCriteria().andEqualTo("userId",user.getUserId());
        List<UserEntity> userEntityList = userMapper.selectByCondition(condition);
        if (!CollectionUtils.isEmpty(userEntityList)){
            String fileId = userEntityList.get(0).getImg();

            Condition fileCondition = new Condition(FileEntity.class);
            fileCondition.createCriteria().andEqualTo("fileId",NumericHelper.toInteger(fileId));
            List<FileEntity> fileEntities = fileMapper.selectByCondition(fileCondition);
            if (!CollectionUtils.isEmpty(fileEntities)){
                FileEntity file = fileEntities.get(0);
                if (!"32".equals(fileId)){
                    fileMapper.deleteByCondition(fileCondition);
                    CosUtils.delete(file.getBucketName(),file.getPath());
                }
            }
            UserEntity userEntity = new UserEntity();
            userEntity.setImg(StringUtils.toString(fileEntity.getFileId()));
            userMapper.updateByConditionSelective(userEntity,condition);
        }
        String imgPath = CosUtils.getImg("picture-1307568725", path);
        return imgPath;
    }

    @Override
    public void changeInfo(UserEntity userEntity) {
        if (userEntity.getUserId() == null){
            return;
        }
        Condition condition = new Condition(UserEntity.class);
        condition.createCriteria().andEqualTo("userId",userEntity.getUserId());
        UserEntity userUpdate = userEntity;
        userUpdate.setUserId(null);
        userMapper.updateByConditionSelective(userUpdate,condition);
    }

    @Override
    public void changePwd(PwdParam param) {
        String userId = param.getUserId();
        String origPwd = param.getOrigPwd();
        String newPwd = param.getNewPwd();
        String reNewPwd = param.getReNewPwd();
        Condition condition = new Condition(UserEntity.class);
        condition.createCriteria().andEqualTo("userId",userId);
        List<UserEntity> userEntityList = userMapper.selectByCondition(condition);
        if (CollectionUtils.isEmpty(userEntityList)){
            throw new BusinessException(ErrorCode.UPDATE_108);
        }
        UserEntity user = userEntityList.get(0);
        if (!user.getPassword().equals(origPwd)){
            throw new BusinessException(ErrorCode.UPDATE_107);
        }

        if (!newPwd.equals(reNewPwd)){
            throw new BusinessException(ErrorCode.UPDATE_109);
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setPassword(newPwd);
        userMapper.updateByConditionSelective(userEntity,condition);
    }
}
